﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reactive.Concurrency;
using System.Reactive.Threading;
using System.Windows.Input;

namespace RxFormsTestbed
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();


            //var xs = Observable.Return(42);

            // var mousedown = Observable.FromEventPattern<MouseEventArgs>(this,"MouseDown");

            var mousedown = from evt in Observable.FromEventPattern<MouseEventArgs>(pictureBox1, "MouseDown")
                            select evt.EventArgs.Location;

            var mouseup = from evt in Observable.FromEventPattern<MouseEventArgs>(pictureBox1, "MouseUp")
                          select evt.EventArgs.Location;

            var mousemove = from evt in Observable.FromEventPattern<MouseEventArgs>(pictureBox1, "MouseMove")
                            select evt.EventArgs.Location;
            
            
            var mousemovement = mousemove.Zip(mousemove.Skip(1),
                                              (prev, curr) => new {X = curr.X - prev.X, Y = curr.Y - prev.Y});

            var q = from md in mousedown
                    from mm in mousemovement.TakeUntil(mouseup)
                    select mm;

            /*var q = from start in mousedown
                    from pos in mousemove.StartWith(start).TakeUntil(mouseup)
                                         
                    select pos;*/


            /*var xs = Observable.Interval(TimeSpan.FromSeconds(1))
                .ObserveOn(WindowsFormsSynchronizationContext.Current)
                .SkipUntil(mousedown)
                .Subscribe(value => label1.Text = value.ToString());*/


            q.ObserveOn(WindowsFormsSynchronizationContext.Current)
                //.Subscribe(value => label1.Text = value.ToString());
             .Subscribe(v =>
                            {
                                pictureBox1.Left += v.X;
                                pictureBox1.Top += v.Y;
                                /*pictureBox1.SetBounds(pictureBox1.Left = v.X, pictureBox1.Top += v.Y,
                                              pictureBox1.Width, pictureBox1.Height));*/
                            });

            q.Subscribe(value => label1.Text = value.ToString());
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
        }

        private void label1_Click(object sender, EventArgs e)
        {
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
        }
    }
}